package com.gengzp.permission.tools;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gengzp.permission.exception.PermissionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.gengzp.permission.constants.PermissionExceptionConstants.INTERNAL_SERVER_ERROR;

/**
 * @ClassName PermissionJsonConverter
 * @Description 权限认证框架json转换器, 依赖jackson库
 * @Author gengzp
 * @Date 2025/8/14 21:59
 */
public class PermissionJsonConverter {

    private static final Logger logger = LoggerFactory.getLogger(PermissionJsonConverter.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private PermissionJsonConverter() {
    }

    /**
     * 将json字符串转换为指定泛型对象
     *
     * @param json  json字符串
     * @param clazz 指定泛型对象类型
     * @param <T>   泛型对象类型
     * @return 指定泛型对象
     */
    public static <T> T convertJsonToObject(String json, Class<T> clazz) throws PermissionException {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            logger.error("json转换异常", e);
            throw PermissionException.get(INTERNAL_SERVER_ERROR, String.format("json转换异常：%s", e.getMessage()));
        }
    }

    /**
     * 将json字符串转换为带指定泛型的对象
     *
     * @param json          json字符串
     * @param typeReference 指定泛型的集合对象类型的typeReference对象
     * @param <T>           泛型对象类型
     * @return 指定泛型的集合对象
     */
    public static <T> T convertJsonToGenericObject(String json, TypeReference<T> typeReference) throws PermissionException {
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (Exception e) {
            logger.error("json转换异常", e);
            throw PermissionException.get(INTERNAL_SERVER_ERROR, String.format("json转换异常：%s", e.getMessage()));
        }
    }

    /**
     * 将对象转为json字符串
     *
     * @param object 对象
     * @return json字符串
     */
    public static String convertObjectToJson(Object object) throws PermissionException {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            logger.error("json转换异常", e);
            throw PermissionException.get(INTERNAL_SERVER_ERROR, String.format("json转换异常：%s", e.getMessage()));

        }
    }

}
